//
//  MLPhotoBrowser.m
//  BrowsePictureDemo
//
//  Created by GZMLUser on 14-11-13.
//  Copyright (c) 2014年 GZMLUser. All rights reserved.
//

#import "MLPhotoBrowser.h"
#import "MLPhoto.h"
#import "MLPhotoView.h"
#import "SDWebImageManager.h"
#import "MLPhotoToolbar.h"
#import "MLPhotoInfo.h"

#define kPadding 10
#define kPhotoViewTagOffset 1000
#define kPhotoViewIndex(photoView) ([photoView tag] - kPhotoViewTagOffset)

@interface MLPhotoBrowser ()<MLPhotoViewDelegate>
{
    // 滚动的view
    UIScrollView *_photoScrollView;
    // 所有的图片view
    NSMutableSet *_visiblePhotoViews;
    NSMutableSet *_reusablePhotoViews;
    // 工具条
    MLPhotoToolbar *_toolbar;

    NSInteger _recodeCurrenIndex;
    UIWindow *window;
}

//! 当前展示的图片索引
@property (nonatomic, assign) NSUInteger currentPhotoIndex;

@end

@implementation MLPhotoBrowser


#pragma mark 初始化方式

- (id)initWithImageArray:(NSArray *)photoArray currentTapedView:(UIImageView *)currentTapedView
{
    if (self = [super init]) {
        self.photos = photoArray;
        
        self.currentPhotoIndex = currentTapedView.tag;
        _recodeCurrenIndex = currentTapedView.tag;
    }
    
    return self;
}
//
//- (void)jugementLoadType // 判断加载类型
//{
//    for (MLPhotoInfo *photo in _photos) {
//        if (photo.photo.path) {
//            _loadType = localeLoad;
//            return;
//        }
//        
//        if (photo.photo.url) {
//            _loadType = netWorkLoad;
//            return;
//        }
//    }
//}

#pragma mark - 设置状态栏及View
- (void)loadView
{
    self.view = [[UIView alloc] init];
    self.view.frame = [UIScreen mainScreen].bounds;
    self.view.backgroundColor = [UIColor blackColor];
    self.view.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        self.view.alpha = 1;
    }];
    
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.创建UIScrollView
    [self createScrollView];
    
    // 2.创建工具条
    [self createToolbar];
}

#pragma mark 显示
- (void)showPhotosWithStatusBarisHiden:(BOOL)hidden indexLabelIsHidden:(BOOL)labelHidden andSaveButtonIsHidden:(BOOL)buttonHidden
{
    // 加载页面
    window = [UIApplication sharedApplication].keyWindow;
    
    if (hidden == YES) {
        window.windowLevel = UIWindowLevelAlert;
    }
    
    [window addSubview:self.view];
    [window.rootViewController addChildViewController:self];
    
    // 如是从第一张开始显示
    if (_currentPhotoIndex == 0) {
        [self showPhotos];
    }
    // 设置toolbar及状态栏
    if (labelHidden == YES) {
        [_toolbar hideIndexLabel];
    }
    if (buttonHidden == YES) {
        [_toolbar hideSaveButton];
    }
}


#pragma mark 创建UIScrollView
- (void)createScrollView
{
    CGRect frame = self.view.bounds;
    frame.origin.x -= kPadding;
    frame.size.width += (2 * kPadding);
    _photoScrollView = [[UIScrollView alloc] initWithFrame:frame];
    _photoScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _photoScrollView.pagingEnabled = YES;
    _photoScrollView.delegate = self;
    _photoScrollView.showsHorizontalScrollIndicator = NO;
    _photoScrollView.showsVerticalScrollIndicator = NO;
    _photoScrollView.backgroundColor = [UIColor clearColor];
    _photoScrollView.contentSize = CGSizeMake(frame.size.width * _photos.count, 0);
    [self.view addSubview:_photoScrollView];
    _photoScrollView.contentOffset = CGPointMake(_currentPhotoIndex * frame.size.width, 0);
}
- (void)createToolbar
{
    CGFloat barHeight = 44;
    CGFloat barY = self.view.frame.size.height - barHeight;
    _toolbar = [[MLPhotoToolbar alloc] init];
    _toolbar.frame = CGRectMake(0, barY, self.view.frame.size.width, barHeight);
    _toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    _toolbar.photos = _photos;
    [self.view addSubview:_toolbar];
    [self.view bringSubviewToFront:_toolbar];
    [self updateTollbarState]; // 设置相关参数
}

#pragma mark 设置图片数组
- (void)setPhotos:(NSArray *)photos
{
    _photos = photos;
    NSMutableArray *photosArray = [NSMutableArray array];
    if (photos.count > 1) {
        _visiblePhotoViews = [NSMutableSet set];
        _reusablePhotoViews = [NSMutableSet set];
    }
    for (int i = 0; i<_photos.count; i++) {
        MLPhoto *photo = _photos[i];
        
        MLPhotoInfo *photos = [[MLPhotoInfo alloc]init];
        photos.photo = photo;
        photos.index = i; // 设置索引
        photos.firstShow = i == _currentPhotoIndex;
        
        [photosArray addObject:photos];
    }
    _photos = photosArray;
}
#pragma mark 设置选中的图片
- (void)setCurrentPhotoIndex:(NSUInteger)currentPhotoIndex
{
    _currentPhotoIndex = currentPhotoIndex;
    
    for (int i = 0; i<_photos.count; i++) {
        MLPhotoInfo *photo = _photos[i];
        photo.firstShow = i == currentPhotoIndex;
    }
    
    if ([self isViewLoaded]) {
        _photoScrollView.contentOffset = CGPointMake(_currentPhotoIndex * _photoScrollView.frame.size.width, 0);
        
        // 显示所有的相片
        [self showPhotos];
    }
}

#pragma mark - MLPhotoView代理
- (void)photoViewSingleTap:(MLPhotoView *)photoView
{
   
    if (window.windowLevel == UIWindowLevelAlert) {
        window.windowLevel = UIWindowLevelNormal;
    }
    
    [UIView animateWithDuration:0.3f animations:^{
        self.view.backgroundColor = [UIColor clearColor];
        
    } completion:nil];
    
    // 移除工具条
    [_toolbar removeFromSuperview];
}

- (void)photoViewDidEndZoom:(MLPhotoView *)photoView
{
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

- (void)photoViewImageFinishLoad:(MLPhotoView *)photoView
{
    
    _toolbar.currentPhotoIndex = _currentPhotoIndex;
}


#pragma mark 显示图片
- (void)showPhotos
{
    // 只有一张图片
    if (_photos.count == 1) {
        [self showPhotoViewAtIndex:0];
        return;
    }
    
    CGRect visibleBounds = _photoScrollView.bounds;
    int firstIndex = (int)floorf((CGRectGetMinX(visibleBounds)+kPadding*2) / CGRectGetWidth(visibleBounds));
    int lastIndex  = (int)floorf((CGRectGetMaxX(visibleBounds)-kPadding*2-1) / CGRectGetWidth(visibleBounds));
    if (firstIndex < 0) firstIndex = 0;
    if (firstIndex >= _photos.count) firstIndex = (int)_photos.count - 1;
    if (lastIndex < 0) lastIndex = 0;
    if (lastIndex >= _photos.count) lastIndex = (int)_photos.count - 1;
    
    // 回收不再显示的ImageView
    NSInteger photoViewIndex;
    for (MLPhotoView *photoView in _visiblePhotoViews) {
        photoViewIndex = kPhotoViewIndex(photoView);
        if (photoViewIndex < firstIndex || photoViewIndex > lastIndex) {
            [_reusablePhotoViews addObject:photoView];
            [photoView removeFromSuperview];
        }
    }
    
    [_visiblePhotoViews minusSet:_reusablePhotoViews];
    while (_reusablePhotoViews.count > 2) {
        [_reusablePhotoViews removeObject:[_reusablePhotoViews anyObject]];
    }
    
    for (NSUInteger index = firstIndex; index <= lastIndex; index++) {
        if (![self isShowingPhotoViewAtIndex:index]) {
            [self showPhotoViewAtIndex:(int)index];
            
            
        }
    }
}

#pragma mark 显示一个图片view
- (void)showPhotoViewAtIndex:(int)index
{
    MLPhotoView *photoView = [self dequeueReusablePhotoView];
    if (!photoView) { // 添加新的图片view
        photoView = [[MLPhotoView alloc] init];
        photoView.photoViewDelegate = self;
    }
    
    // 调整当期页的frame
    CGRect bounds = _photoScrollView.bounds;

    CGRect photoViewFrame = bounds;
    photoViewFrame.size.width -= (2 * kPadding);
    photoViewFrame.origin.x = (bounds.size.width * index) + kPadding;
    photoView.tag = kPhotoViewTagOffset + index;
    MLPhotoInfo *photo = _photos[index];

    photoView.frame = photoViewFrame;
    photoView.photos = photo;

    [_visiblePhotoViews addObject:photoView];
    [_photoScrollView addSubview:photoView];
    
    [self loadImageNearIndex:index];
}
#pragma mark 加载index附近的图片
- (void)loadImageNearIndex:(int)index
{
    if (index > 0) {
        MLPhotoInfo *photo = _photos[index - 1];
        if (photo.photo.url != nil) {
            [[SDWebImageManager sharedManager] downloadImageWithURL:photo.photo.url options:SDWebImageLowPriority|SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            }];
        }
        
    }
    
    if (index < _photos.count - 1) {
        MLPhotoInfo *photo = _photos[index + 1];
        if (photo.photo.url != nil) {
            [[SDWebImageManager sharedManager] downloadImageWithURL:photo.photo.url options:SDWebImageLowPriority|SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                
            }];
        }
    }
}
#pragma mark index这页是否正在显示
- (BOOL)isShowingPhotoViewAtIndex:(NSUInteger)index {
    for (MLPhotoView *photoView in _visiblePhotoViews) {
        if (kPhotoViewIndex(photoView) == index) {
            return YES;
        }
    }
    return  NO;
}

#pragma mark 循环利用某个view
- (MLPhotoView *)dequeueReusablePhotoView
{
    MLPhotoView *photoView = [_reusablePhotoViews anyObject];
    if (photoView) {
        [_reusablePhotoViews removeObject:photoView];
    }
    return photoView;
}

#pragma mark 更新toolbar状态
- (void)updateTollbarState
{
    [_toolbar showToolbar];
    _currentPhotoIndex = _photoScrollView.contentOffset.x / _photoScrollView.frame.size.width;
    _toolbar.currentPhotoIndex = _currentPhotoIndex;
    
  //  [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hideToolbar:) userInfo:nil repeats:NO];
}

#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self showPhotos];
    [self updateTollbarState];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    [self updateTollbarState];

}
- (void)hideToolbar:(NSTimer *)timer
{
    [_toolbar hideToolbar];
    [timer invalidate];
}

@end
